package com.train.common.utils.string;

import cn.hutool.core.util.StrUtil;
import com.train.common.utils.collection.CollectionUtils;
import com.train.common.utils.convert.StrConvertUtils;

/**
 * 字符串格式化工具
 */
public class FormatterUtils {

    public static final String CURLY_BRACES = "{}";

    /**
     * 指定以{}为占位符进行字符串格式化
     * @param format
     * @param args
     * @return
     */
    public static String format(String format, Object... args) {
        if (StrUtil.isEmpty(format) || CollectionUtils.isEmpty(args)) {
            return format;
        }
        StringBuilder builder = new StringBuilder();
        int position = 0;
        for (Object arg : args) {
            int index = format.indexOf(CURLY_BRACES, position);
            if (index == -1) {
                if (position == 0) {
                    return format;
                } else {
                    builder.append(format.substring(position));
                    return builder.toString();
                }
            } else {
                builder.append(format, position, index).append(StrConvertUtils.utf8Str(arg));
                position = index + 2;
            }
        }
        if (position < format.length()) {
            builder.append(format.substring(position));
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        System.out.println(format("hello,{}, {}, nihao", "jack", "world"));
    }
}
